package org.visionlibrary.image.filters.rescaling;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class Sepia extends AbstractFilter {
	public TiledImage applyFilter(TiledImage src, TiledImage dest) {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src);

		if (src.getNumBands() != 3)
			throw new IllegalArgumentException(
					"Wrong number of channels. This filter can be applied only to rgb images.");

		int maxX = src.getWidth();
		int maxY = src.getHeight();

		for (int x = 0; x < maxX; x++)
			for (int y = 0; y < maxY; y++) {
				int r = src.getSample(x, y, 0); // I hope tha this is red
												// channel
				int g = src.getSample(x, y, 1);
				int b = src.getSample(x, y, 2);
				int newR = (int) (((float) r * 0.393f + (float) g * 0.769f + (float) b * 0.189f) / 1.351f);
				int newG = (int) (((float) r * 0.349f + (float) g * 0.686f + (float) b * 0.168f) / 1.203f);
				int newB = (int) (((float) r * 0.272f + (float) g * 0.534f + (float) b * 0.131f) / 2.140f);

				dest.setSample(x, y, 0, normalization.normalize(newR));
				dest.setSample(x, y, 1, normalization.normalize(newG));
				dest.setSample(x, y, 2, normalization.normalize(newB));
			}

		return dest;
	}
}
